#include <init.h>
#include "dataword.h"
#include "utilfile.h"
#include <iostream>
#include <QtSql>
#include <QtDebug>
#include "sql.h"

void Init::initDb()
{
    const QList<Word> words = FileUtil::loadWordsFormFile("编程常见词库.txt");
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("rushword.db");

    bool flag = db.open();
    if(!flag)
    {
        std::cout << "failed to open database" << std::endl;
        return ;
    }

    QSqlQuery query;
//    query.exec("drop table if exists word");
    //创建词汇表
    query.prepare(SQL_CREATETABLE_VOCABULARY);
    flag = query.exec();
    if(!flag)
    {
        std::cout << "failed to create table" << std::endl;
        return ;
    }

//    插入词汇表数据
    query.prepare(SQL_INSERT_VOCABULARY);
    query.addBindValue("编程常见词库");
    int sizes = words.length();
    query.addBindValue(sizes);
    query.exec();

    //查询词汇表数据
    query.prepare(SQL_SELECT_VOCABULARY_ALL);
    query.exec();
    while(query.next())
    {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        int size = query.value(2).toInt();

        qDebug()<<id<<","<<name<<","<<size;
    }

    //创建单词表
    query.prepare(SQL_CREATETABLE_WORD);
    flag = query.exec();
    if(!flag)
    {
        std::cout << "failed to create table" << std::endl;
        return ;
    }
    //插入单词数据
    query.prepare(SQL_INSERT_WROD);
    for(auto& word : words)
    {
        query.addBindValue(QString::fromStdString(word.original()));
        query.addBindValue(QString::fromStdString(word.translation()));
        query.addBindValue(1);
        query.exec();
    }
    //查询单词表数据
    query.prepare(SQL_SELECT_WORD_ALL);
    query.exec();
    while(query.next())
    {
        int id = query.value(0).toInt();
        QString original = query.value(1).toString();
        QString translation = query.value(2).toString();
        int vocabularyId = query.value(3).toInt();
        qDebug()<<id<<","<<original<<","<<translation<<","<<vocabularyId;
    }

    //创建用户表
    query.prepare(SQL_CREATETABLE_USER);
    flag = query.exec();
    if(!flag)
    {
        std::cout << "failed to create table" << std::endl;
        return ;
    }

    //插入用户数据
    query.prepare(SQL_INSERT_USER);
    query.addBindValue(-1);
    query.addBindValue(-1);
    query.addBindValue(0);

    flag = query.exec();
    if(!flag)
    {
        std::cout << "failed to insert user" << std::endl;
        return ;
    }

    db.close();
}
